package app.blog.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import slap.mvc.scope.RenderModels;
import slap.paradigm.Function;
import slap.util.Regex;

import app.blog.entity.Article;
import app.blog.service.filter.Filter;
import app.blog.service.filter.TheContentFilter;

import jodd.util.collection.SortedArrayList;

public class Articles {
	
	public static class ArticleVO{
		public String title;
		public String author;
		public String cats;
		public String tags;
		public String pub_date;
		public int views;
		
		public String edit_link;
		public String the_permalink;
		
		public String content;
		
		public int comments_number;
		
		public ArticleVO(Article art){
			this.title = art.title;
			this.cats = Categories.the_category(art);
			this.tags = Tags.the_tag(art);
			this.pub_date = Miscs.the_time("y年 M月 d日, h:m", art.pubDate);
			this.views = 0;
			this.content = the_content(art);
			this.edit_link = "#";
			this.the_permalink = "#";
			this.comments_number = 0;
		}
	}
	
	private static final String MORE_TAG = "<!--more-->";
	private static final String BR_TAG = "<br />\n";
	private static final Pattern BQ = Pattern.compile(
			"(?s)<blockquote>.*blockquote>", Pattern.MULTILINE);
	private static Map<Class<?>, SortedArrayList<Filter>> filters = new HashMap<Class<?>, SortedArrayList<Filter>>();

	public static void add_filter(Filter filter) {
		SortedArrayList<Filter> stack = filters.get(filter.getClass());
		if (stack == null) {
			stack = new SortedArrayList<Filter>();
			filters.put(filter.getClass(), stack);
		}
		stack.add(filter);
	}

	public static List<ArticleVO> recent_articles(int n) {
		List<Article> articles = Article.recent(n);
		List<ArticleVO> vos = new ArrayList<ArticleVO>(articles.size());
		for(Article art : articles){
			vos.add(new ArticleVO(art));
		}
		return vos;
	}

	public static String the_content(Article article) {
		String output = article.content;

		output = Regex.reg_replace(BQ, output, new Function<String, Matcher>() {
			public String invoke(Matcher matcher) {
				return matcher.group().replaceAll("\n", BR_TAG);
			}
		});

		if (RenderModels.current().get("is_single", Boolean.class)) {
			return output;
		}
		int more = output.indexOf(MORE_TAG);
		if (more > 0) {
			output = output.substring(0, more);
		}

		output = output + "<a href='#' class='more-link'>Read more</a>";
		SortedArrayList<Filter> fl = filters.get(TheContentFilter.class);
		if (fl != null) {
			for (Filter filter : fl) {
				filter.do_filter(output);
			}
		}

		return output;
	}

	public static ArticleVO getById(int id) {
		Article art = Article.getById(id);
		if (art == null){
			return null;
		}
		return new ArticleVO(art);
	}

}